import { ProList } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Avatar, Button, Tag, Typography } from 'antd';
import { useEffect, useState } from 'react';
import { getTrippingRecordListPaginated } from '@/pages/DormTrippingRecord/api';
import { TrippingRecordModel } from '@/pages/DormTrippingRecord/types';

export default function TrippingRecordList() {
  const [pendingRecords, setPendingRecords] = useState<TrippingRecordModel[]>([]);

  // 获取待处理的跳闸记录
  const { loading, run: fetchPendingRecords } = useRequest(
    async () => {
      const res = await getTrippingRecordListPaginated({
        current: 1,
        pageSize: 5,
        isHandled: 0, // 0-未处理，1-已处理
      });
      if (res.code === 200 && res.data) {
        setPendingRecords(res.data.records || []);
      }
      return res;
    },
    {
      manual: true,
      onError: (error) => {
        console.error('获取待处理跳闸记录失败:', error);
      },
    },
  );

  useEffect(() => {
    fetchPendingRecords();
  }, []);

  // 格式化时间
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(
      date.getDate(),
    ).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(
      date.getMinutes(),
    ).padStart(2, '0')}`;
  };

  return (
    <>
      <Typography.Title level={5}>待处理跳闸记录</Typography.Title>
      <ProList<TrippingRecordModel>
        pagination={false}
        dataSource={pendingRecords}
        ghost
        loading={loading}
        rowKey="id"
        metas={{
          title: {
            dataIndex: 'dormitoryNum',
            render: (text) => <Typography.Text copyable>{text}</Typography.Text>,
          },
          subTitle: {
            render: (_, record) => {
              const status = record.isHandled === 1 ? 'success' : 'error';
              const text = record.isHandled === 1 ? '已处理' : '未处理';
              return <Tag color={status}>{text}</Tag>;
            },
          },
          avatar: {
            render: () => <Avatar style={{ backgroundColor: '#f56a00' }}>宿</Avatar>,
          },
          description: {
            render: (_, record) => (
              <span>
                <span>学生：{record.studentName}</span>
                <span style={{ marginLeft: 8 }}>班级：{record.className}</span>
                <br />
                <span>跳闸功率：{record.trippingPower}kW</span>
                <span style={{ marginLeft: 8 }}>
                  跳闸时间：{formatDate(record.trippingTime)}
                </span>
              </span>
            ),
          },
          actions: {
            render: () => [
              <Button key="handle" type="link" size="small">
                处理
              </Button>,
            ],
          },
        }}
      />
    </>
  );
}